<template>
  <base-breadcrumb class="satisfactionsurvey">
    <searchData ref="searchData" :search-data="searchArr" @search="search" />
    <a-card :bordered="false">
      <div class="table-operator">
        <div class="pub-table-action-btn pub-table-action-btn-1">
          <a-button v-btnPermission="'crm_006_pus_02'" type="primary" @click="handlePush"> 推送局平台 </a-button>
          <a-button v-btnPermission="'crm_006_cho_05'" type="primary" @click="handleCheckUser"> 选择业主填报人员 </a-button>
        </div>
      </div>
      <list-table ref="table"  :loading="loading" :pagination="false"
       :columns="columns"  :request="loadData"  row-key="id"
        :export-config="{ use: true, select: '技术服务需求', all: '技术服务需求',customColumns: columns}"
        @select-click="(e) => (selectedRow = e.rows)"
       >
        <template slot="status" slot-scope="text, record">
          <list-status :color="{ 0: 'yellow', 1: 'blue', 2: 'green' }[record.status]" conversion="en" :text="text" />
        </template>
        <div slot="operation" slot-scope="text, record">
          <MoreButton>
            <a v-btnPermission="'crm_006_loo_01'" @click="handleEdit(record, 3)">查看</a>
            <a v-if="record.status == 1" v-btnPermission="'crm_006_con_03'" @click="handleSure(record.id)">确定</a>
            <a v-if="record.status == 2 && record.pushStatus == 0" v-btnPermission="'crm_006_edi_04'" @click="() => handleEdit(record, 2)">编辑</a>
          </MoreButton>
        </div>
      </list-table>

    </a-card>

    <a-modal v-if="checkShow" title="选择业主填报人员" :visible="checkShow" width="60%" @cancel="clearUser">
      <a-form-model ref="RuleForm" :model="formData" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules">
        <a-row>
          <a-col span="12">
            <a-form-model-item label="所属分公司" prop="branchComId">
              <SelectSubCompany ref="selectSubCompany" v-model="formData.branchComId" placeholder="请选择" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="项目名称" prop="projectId">
              <SelectProject ref="selectProject" v-model="formData.projectId" placeholder="请选择" :form="formData" key-value="branchComId" @change="getProJectOwner" />
            </a-form-model-item>
          </a-col>
          <a-col span="12">
            <a-form-model-item label="调查业主" prop="ownerId">
              <a-select v-model="formData.ownerId" :loading="ownerLoad" placeholder="请选择">
                <a-select-option v-for="item in ownerData" :key="item.id" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col span="24">
            <a-form-model-item extra="提示:如果没有业主，请到工程/工程项目管理/业主登录信息中进行设置" />
          </a-col>
        </a-row>
      </a-form-model>

      <template slot="footer">
        <a-button @click="clearUser"> 取消 </a-button>
        <a-button :loading="bindLoading" type="primary" @click="submitUser"> 提交 </a-button>
      </template>
    </a-modal>
  </base-breadcrumb>
</template>
<script>
// import { getComplaintList, customerComplaintCancel, queryComplaintTree } from '@/api/complaint'
import { bindingOwner, queryOwnerInfo, queryBindingOwner, getSurveyList, comfirmSurvey, batchPushSurvey } from '@/api/complaint/satisfactionsurvey.js'
import listStatus from '@/components/list_status/list_status'
import SelectProject from '@/components/Select/SelectProject' // 项目名称
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject'
import OrgTreeSelect from '@/components/OrgTreeSelect'
export default {
  name: 'a' + Date.now(),
  data: function () {
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      ownerData: [],
      loading: false,
      bindLoading: false,
      ownerLoad: false,
      infoShow: false,
      checkShow: false,
      pathName: this.$route.path,
      queryParam: {},
      infoQueryParam: {},
      pageNo: 1,
      pageSize: 10,
      totalSize: 0,
      selectedRow: [],
      searchArr: [
          {
          name: '所属单位',
          valueKey: 'searchQuery',
          type: OrgTreeSelect,
        },
        // {
        //   name: '所属组织',
        //   valueKey: 'statisticsId',
        //   type: SelectCompanyAndProject
        // },
        // {
        //   name: '所属分公司',
        //   valueKey: 'branchComId',
        //   type: SelectSubCompany
        // },
        // {
        //   name: '项目名称',
        //   type: SelectProject,
        //   keyValue: 'branchComId',
        //   valueKey: 'projectId'
        // },
        {
          name: '项目业态',
          value: 'code',
          type: 'input'
        },
        {
          name: '项目状态',
          value: 'projectStatus',
          type: 'select',
          data: [
            {
              value: '0',
              label: '立项中'
            },
            {
              value: '1',
              label: '施工准备阶段'
            },
            {
              value: '2',
              label: '在建'
            },
            {
              value: '3',
              label: '停工'
            },
            {
              value: '4',
              label: '停缓建'
            },
            {
              value: '5',
              label: '维保期'
            },
            {
              value: '5',
              label: '维保期截止'
            }
          ]
        },
        {
          name: '调查月份',
          value: 'surveyMonth',
          type: 'month',
          attrs: {
            valueFormat: 'YYYY-MM'
          }
        },
        {
          name: '状态',
          value: 'status',
          type: 'select',
          data: [
            {
              value: '0',
              label: '待评价'
            },
            {
              value: '1',
              label: '未确认'
            },
            {
              value: '2',
              label: '已确认'
            }
          ]
        },
        {
          name: '推送状态',
          value: 'pushStatus',
          type: 'select',
          data: [
            {
              value: '0',
              label: '未推送'
            },
            {
              value: '1',
              label: '已推送'
            }
          ]
        }
      ],
      columns: [
        {
          title: '所属分公司',
          dataIndex: 'branchComName',
          width: 160
        },
        {
          title: '项目名称',
          dataIndex: 'projectName',
          width: 220
        },
        {
          title: '项目状态',
          dataIndex: 'projectStatusName',
          width: 160
        },

        {
          title: '调查月份',
          dataIndex: 'surveyMonth',
          width: 160
        },
        {
          title: '总分',
          dataIndex: 'totalSorce',
          width: 160
        },
        {
          title: '推送状态',
          width: 160,
          dataIndex: 'pushStatusName'
        },
        {
          title: '状态',
          width: 160,
          dataIndex: 'statusName',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 200,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      selectedRowKeys: [],
      selectId: [],
      selectedRows: [],
      chooseData: 0,
      tableData: [],
      projectData: [],
      formData: {
        ownerId: '',
        projectId: '',
        branchComId: ''
      },
      rules: {
        projectId: { required: true, message: '请选择项目名称', trigger: 'change' },
        branchComId: { required: true, message: '请选择所属分公司', trigger: 'change' },
        ownerId: { required: true, message: '请选择调查业主', trigger: 'change' }
      },
      loadData: (parameter) => {
          let that = this
          parameter.pageNum = parameter.pageNo;
          delete parameter.pageNo;
          this.loading = true;
          const requestParameters = Object.assign({}, parameter, { param: that.queryParam })
          return getSurveyList(requestParameters).then((res) => {
          let list = res.data?.list;
          list.length && list.map((item)=>{
             if(!item.pushStatus || item.pushStatus * 1 !== 0 || !item.status || item.status * 1 !== 2){
                item.disabled = true;
             }
          })
          this.loading = false;
          return { code: 200, data: list, totalSize: res.data?.total }
          })
        },
    }
  },
  components: {
    SelectSubCompany,
    SelectProject,
    listStatus
  },
  watch: {
    $route(to, from) {
      if (to.params) {
        from.path === '/complaint/statistics' && this.$refs.searchData?.form.resetFields()
        this.$refs.searchData?.form.setFieldsValue(to.params)
        this.$refs.searchData?.search()
        // this.search(JSON.parse(to.params))
      }
    }
  },
  created() {
    if (!this.$route.params || (this.$route.params instanceof Object && !Object.keys(this.$route.params)?.length)) {
      this.list()
    }
  },
  mounted: function () {
    if (this.$route.params) {
      const data = this.$route.params
      this.$refs.searchData?.form.setFieldsValue(data)
      this.$refs.searchData?.search()
    }
    this.$bus.$on('handleRefresh' + this.pathName, () => {
      this.list()
    })
  },
  beforeDestroy() {
    this.$bus.$off('handleRefresh' + this.pathName)
  },
  methods: {
    /**
     * @description: 请求业主列表以及已绑定业主
     */
    async getProJectOwner() {
      this.formData.ownerId = ''
      this.ownerLoad = true
      // 根据项目请求业主列表
      const res = await queryOwnerInfo({ projectId: this.formData.projectId }).finally(()=>{
          this.ownerLoad = false
      })
      if (res.code === 200) {
        this.ownerData = res.data || []
      }
      // 根据项目请求已绑定业主回显
      queryBindingOwner({ projectId: this.formData.projectId }).then(res => {
        if (res.code === 200) {
          this.$set(this.formData, 'ownerId', res.data.ownerId)
        }
      })
    },
    handlePush() {
      let that = this
      if (this.selectedRow.length == 0) {
        this.$message.error('请选择数据!')
      } else {
        that.$confirm({
          title: '温馨提示',
          content: '是否确认推送?',
          okText: '确认',
          cancelText: '取消',
          onOk() {
            that.surePush()
          }
        })
      }
    },
    surePush() {
      let idList = []
      idList = this.selectedRow.map((item=>item.id)) || []
      this.loading = true
      let that = this
      batchPushSurvey({ idList })
        .then((res) => {
          if (res.data) {
            that.$message.success('推送局平台成功')
            this.loading = false
            that.selectedRow = []
            that.list()
          } else {
            this.loading = false
          }
        })
        .catch((err) => {
          this.loading = false
        })
    },
    clearUser() {
      this.checkShow = false
      this.formData = {
        id: null,
        ownerId: '',
        projectId: ''
      }
    },
    submitUser() {
      this.$refs.RuleForm.validate((valid) => {
        if (valid) {
          const data = {
            id: null,
            ownerId: this.formData.ownerId,
            projectId: this.formData.projectId
          }
          this.bindLoading = true
          bindingOwner(data).then((res) => {
            if (res.data.code == 200) {
              this.checkShow = false
              this.formData = {
                ownerId: '',
                projectId: '',
                branchComId: ''
              }
            }
            this.bindLoading = false
          })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    handleCheckUser() {
      // if (this.selectedRowKeys.length == 0) {
      //   this.$message.error('请选择数据!')
      // } else {
      this.checkShow = true
      // this.getCode()
      // }
    },
    getInfoShow(record) {
      if (record.complaintConsult <= 0) {
        return false
      } else {
        this.infoQueryParam = {
          statusList: ['2', '4'],
          infoId: record.infoId
        }
        this.infoShow = true
      }
    },
    list(callback) {
      // this.loading = true
      // let _this = this
      // const searchData = {
      //   pageSize: callback ? _this.totalSize : _this.pageSize,
      //   pageNum: _this.pageNo,
      //   param: this.queryParam
      // }
      // getSurveyList(searchData).then((res) => {
      //   if (res.code === 200) {
      //     if (callback) {
      //       if (res.data.list.length) {
      //         callback(res.data.list)
      //       }
      //       this.loading = false
      //       return
      //     }
      //     _this.tableData = res.data.list
      //     _this.totalSize = res.data.total
      //   }
      //   this.loading = false
      // })
    },
    search(val) {
      this.queryParam = { ...val }
      this.$refs.table.refresh()
      this.list()
    },
    handlePageChange(pageNo, pageSize) {
      this.pageNo = pageNo
      this.list()
      this.selectedRow = []
    },
    showSizeChange(pageNo, pageSize) {
      this.pageNo = 1
      this.pageSize = pageSize
      this.list()
    },
    handleSure(id) {
      let that = this
      that.$confirm({
        title: '温馨提示',
        content: '是否确认?',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          return comfirmSurvey(id)
            .then((res) => {
              that.$message.success('确认成功！')
              that.list()
              that.$refs.table.refresh(true)
            })
            .catch((err) => {
              console.log(err)
            })
        }
      })
    },
    handleEdit(record, state) {
      this.infoShow = false
      this.$router.push({
        name: 'AddSatisfactionsurvey',
        query: {
          id: (record && record.id) || '',
          state: state
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
// /deep/.ant-modal {
//   width: 900px !important;
// }
.searchTable {
  .form_flex {
    display: flex;
    justify-content: space-between;
  }
}
.satisfactionsurvey{
    @{deep} .pub-table-action-btn{
    display: none;
  }
   @{deep} .pub-table-action-btn-1{
    display: inline-block;
  }
}
</style>
